import { Component, OnInit } from '@angular/core';
import { LocalStorage } from '@core/local.storage';
import { ApiService } from '../../../../core/api.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { FormBuilder, FormControl, FormGroup, AbstractControl } from '@angular/forms';
import { DatePipe } from '@angular/common';

@Component({
    selector: 'app-sxdgl',
    templateUrl: './sxdgl.component.html',
    styleUrls: ['./sxdgl.component.less']
})

export class SxdglComponent implements OnInit {
    userInfo = JSON.parse(this.ls.get('loginInfo'));
    dateFormat = 'yyyy/MM/dd HH:mm:ss';
    validateForm: FormGroup;
    lockHeadScroll = { y: window.innerHeight - 350 + 'px' };
    isMainPage = true;
    lastNode: any;
    checkStatus = [];
    data = {
        tableData: [],
        tableTotal: 0,
        tablePagination: {
            page: 0,
            rows: 10,
        },
        detailInfo: {
            index: 0,
            data: []
        },
        ctrlNames: {
            bm: 'bm',
            fzr: 'fzr',
            ys: 'ys',
            sjStart: 'sjStart',
            sjEnd: 'sjEnd',
        },
        nodes: [],
        bjtj: { allalert: 0, ckalert: 0 },
    };



    constructor(public ls: LocalStorage,
        private apiService: ApiService,
        private message: NzMessageService,
        private formBuilder: FormBuilder,
        private modalService: NzModalService,
        private datePipe: DatePipe
    ) { }

    ngOnInit() {
        this.validateForm = this.formBuilder.group({});
        this._addControls();
        this.getBm();
        this.getBjTj();
        this.query();
    }

    _addControls() {
        const values = Object.values(this.data.ctrlNames);
        values.forEach(el => {
            this.validateForm.addControl(el, new FormControl());
        });
    }

    stringEqual(obj1: object, obj2: object) {
        const str1 = JSON.stringify(obj1);
        const str2 = JSON.stringify(obj2);
        return str1 == str2;
    }

    getBm() {
        this.apiService.gjqdgl_dispatcher(
            'sxdgl_bm', {}, 'query', 'post'
        ).subscribe(res => {
            let _data;
            if (typeof res == 'string') {
                _data = JSON.parse(res);
            } else {
                _data = res;
            }
            this.data.nodes = _data.filter(el => el.children);
            this.data.nodes.unshift({
                title: '全部',
                // key: '',
                // children:[]
            });
        });
    }

    /**
     *
            参数名	类型	是否必填	说明
            classid	String	是	部门ID
            leadername	String 	是	用户账号
            level	String 	是	用户等级
            ddl_status	String 	否	是否有丢失，是，否
            startTime	String	否	选填，yyyy-MM-dd
            endTime	Stirng 	否	选填，yyyy-MM-dd
            Sign	String 	是	MD5(classid+ level+秘钥)
            page	String	是	分页
     */
    query(reset: boolean = false) {
        if (reset == true || this.data.tablePagination.page == 0) {
            this.data.tablePagination.page = 1;
        }
        const vfv = this.validateForm.value;
        const ctrlNames = this.data.ctrlNames;
        const param: any = {};
        if (this.lastNode && this.lastNode.key) {
            param.classid = this.lastNode.key || '';
        }
        param.startTime = this.datePipe.transform(vfv[ctrlNames.sjStart], 'yyyy-MM-dd') || '';
        param.endTime = this.datePipe.transform(vfv[ctrlNames.sjEnd], 'yyyy-MM-dd') || '';
        if (param.endTime) {
            param.endTime += ' 23:59:59';
        }
        param.leadername = vfv[ctrlNames.fzr] || '';
        param.ddl_status = vfv[ctrlNames.ys] || '';
        param.page = this.data.tablePagination.page;
        param.rows = this.data.tablePagination.rows;
        this.apiService.gjqdgl_dispatcher(
            'sxdgl_table', { query: param }, 'query', 'post'
            // 'sxdgl_table', param, 'query', 'post'
        ).subscribe(res => {
            let _data;
            if (typeof res == 'string') {
                _data = JSON.parse(res);
            } else {
                _data = res;
            }
            if (_data.data) {
                this.checkStatus = new Array(_data.data.length);
                this.checkStatus.fill(false, 0, _data.data.length);
            }
            this.data.tableTotal = _data.totalCount;
            this.data.tableData = _data.data || [];
        });
    }

    getBjTj() {
        this.apiService.gjqdgl_dispatcher(
            'gjqdgl_bjtj', {}, 'query', 'post'
        ).subscribe(res => {
            let _data;
            if (typeof res == 'string') {
                _data = JSON.parse(res);
            } else {
                _data = res;
            }
            this.data.bjtj = _data.data;
        });
    }

    delete_all() {
        const ids = [], tasknames = [];
        for (let index = 0; index < this.checkStatus.length; index++) {
            const checked = this.checkStatus[index];
            if (checked) {
                const id = this.data.tableData[index].id;
                const taskname = this.data.tableData[index].taskname;
                tasknames.push(taskname);
                ids.push(id);
            }
        }
        this.modalService.confirm({
            nzTitle: '<i>确认审核以下项目吗</i>',
            nzContent: `<b>${tasknames.join('<br>')}</b>`,
            nzOnOk: () => {
                this.delete(ids);
            }
        });
    }

    delete(ids) {
        this.apiService.gjqdgl_dispatcher(
            'sxdgl_table', { id: ids.join(',') }, 'del', 'post'
        ).subscribe(res => {
            let _data;
            if (typeof res == 'string') {
                _data = JSON.parse(res);
            } else {
                _data = res;
            }
            if (_data.code == 'success') {
                this.message.create('success', '删除成功');
            } else {
                this.message.create('error', '删除失败');
            }
            this.query(false);
        });
    }

    nzTreeClick($e: any): void {
        this.lastNode = $e.node;
    }

    nzPageIndexChange() {
        if (this.data.tablePagination.page == 0) {
            return;
        }
        this.query();
    }

    setPageSize() {
        this.query(true);

    }

    changePage(index: number = 0) {
        this.isMainPage = !this.isMainPage;
        if (this.isMainPage) {
            return;
        }
        this.data.detailInfo.index = index;
        this.data.detailInfo.data = this.data.tableData[index].WordTools;
        const detailData = this.data.detailInfo.data;
        if (detailData) {
            detailData.forEach(el => {
                el.outtoolItems = el.OutToolInfo.replace(/\[\w*\]/g, '').split(',');
            });
        }
    }

}
